package cn.schoolwow.flow.monitor.module.business.testcase.flow;

import cn.schoolwow.ams.domain.option.QuickAMSOption;
import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.flow.monitor.domain.TestCaseFlow;
import cn.schoolwow.flow.monitor.module.business.testcase.domain.TestCaseFlowContext;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.queryPackage.QueryPackage;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class GetTestCaseContextListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);
        FlowMonitorOption flowMonitorOption = applicationContext.getBean(FlowMonitorOption.class);
        QuickAMSOption quickAMSOption = applicationContext.getBean(QuickAMSOption.class);
        List<String> categoryNameList = flowContext.getData("categoryNameList", List.class);

        List<TestCaseFlowContext> testCaseFlowContextList = new ArrayList<>();
        List<TestCaseFlow> testCaseFlowList = QueryPackage.newQuery(flowMonitorOption.basePackageName)
                .addClassQuery(TestCaseFlow.class)
                .execute()
                .getInstanceList(TestCaseFlow.class);
        for(TestCaseFlow testCaseFlow:testCaseFlowList){
            try {
                TestCaseFlowContext testCaseFlowContext = new TestCaseFlowContext();
                testCaseFlowContext.name = testCaseFlow.name();
                testCaseFlowContext.categoryName = "其他";
                testCaseFlowContext.testCaseFlow = testCaseFlow;

                String className = testCaseFlow.getClass().getName();
                for(Map.Entry<String,String> entry:quickAMSOption.packageNameLabelMap.entrySet()){
                    if(className.startsWith(entry.getKey())){
                        testCaseFlowContext.categoryName = entry.getValue();
                        break;
                    }
                }
                if(null!=categoryNameList&&!categoryNameList.contains(testCaseFlowContext.categoryName)){
                    continue;
                }
                testCaseFlowContextList.add(testCaseFlowContext);
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
        flowContext.putTemporaryData("testCaseFlowContextList", testCaseFlowContextList);
    }

    @Override
    public String name() {
        return "获取测试用例上下文记录列表";
    }
}
